package com.mdz.myapplication.Controller;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdz.myapplication.Entity.Yhxx;
import com.mdz.myapplication.Mapper.YhxxMapper;
import com.mdz.myapplication.MyapplicationApplication;
import com.mdz.myapplication.View.TempHzView;
import cn.hutool.crypto.SecureUtil;
import de.felixroske.jfxsupport.FXMLController;
import de.felixroske.jfxsupport.GUIState;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;

import static com.mdz.myapplication.utils.RSAUtils.readPrivateKeyFromPem;
import static com.mdz.myapplication.utils.RSAUtils.readPublicKeyFromPem;

/**
 * <p>
 * 人员信息表 前端控制器
 * </p>
 *
 * @author 孟德志
 * @since 2021-11-07
 */
@FXMLController
public class YhxxController implements Initializable {

	@FXML
	private TextField userName;
	@FXML
	private PasswordField passwordField;

	@FXML
	private Button loginbtn;

	private ResourceBundle resourceBundle;

	@Autowired
	private YhxxMapper yhxxMapper;

	@Value(value = "${gsbh}")
	private String gsbh;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		resourceBundle = resources;
	}


	@FXML
	private void handleSubmitButtonAction() {
		String userNameStr = userName.getText().trim();
		String passwordStr = passwordField.getText().trim();
		Alert alert = new Alert(Alert.AlertType.INFORMATION);
		alert.setHeaderText(null);
		if (userNameStr.isEmpty() && passwordStr.isEmpty()) {
			alert.setContentText("用户名和密码不能为空！");
			alert.showAndWait();
			return;
		} else if (userNameStr.isEmpty()) {
			alert.setContentText("用户名不能为空！");
			alert.showAndWait();
			return;
		} else if (passwordStr.isEmpty()) {
			alert.setContentText("密码不能为空！");
			alert.showAndWait();
			return;
		}
//		Integer num = yhxxMapper.selectList(new QueryWrapper<Yhxx>().eq("login_name", userNameStr)).size();
		List<Yhxx> yhxxList = yhxxMapper.selectList(new QueryWrapper<Yhxx>().eq("login_name", userNameStr));
		if (yhxxList.size() < 1) {
			alert.setContentText("用户名错误，请检查用户名！");
			alert.showAndWait();
		}else {

		}


//		if (num < 1) {
//			alert.setContentText("用户名错误，请检查用户名！");
//			alert.showAndWait();
//		} else {
//			List<Yhxx> info = checkLogin(userNameStr, passwordStr);
//			// 登录
//			System.out.println(info.size());
//			if (info.size() >= 1) {
//				GUIState.getScene().setRoot(successpage());
//				GUIState.getStage().setWidth(1000);
//				GUIState.getStage().setHeight(700);
////                GUIState.getStage().setX(150);
////                GUIState.getStage().setY(50);
//				GUIState.getStage().centerOnScreen();
//				GUIState.getStage().setResizable(true);
//			} else {
//				alert.setContentText("请输入正确的密码！");
//				alert.showAndWait();
//			}
//		}
	}


	@FXML
	private void SubmitButtonAction() {
		String userNameStr = userName.getText().trim();
		String passwordStr = passwordField.getText().trim();
		Alert alert = new Alert(Alert.AlertType.INFORMATION);
		alert.setHeaderText(null);
		if (userNameStr.isEmpty() && passwordStr.isEmpty()) {
			alert.setContentText("用户名和密码不能为空！");
			alert.showAndWait();
			return;
		} else if (userNameStr.isEmpty()) {
			alert.setContentText("用户名不能为空！");
			alert.showAndWait();
			return;
		} else if (passwordStr.isEmpty()) {
			alert.setContentText("密码不能为空！");
			alert.showAndWait();
			return;
		}
		System.out.println("yhxxMapper的值为："+yhxxMapper);
		List<Yhxx> yhxxList = yhxxMapper.selectList(new QueryWrapper<Yhxx>().eq("login_name", userNameStr));
//		if (num < 1) {
//			alert.setContentText("用户名错误，请检查用户名！");
//			alert.showAndWait();
//		} else {
//			List<Yhxx> info = checkLogin(userNameStr, passwordStr);
//			// 登录
//			if (info.size() >= 1) {
////                loginbtn.setOnAction(event -> ((Stage) (loginbtn.getScene().getWindow())).close());
//				Stage stage = (Stage) loginbtn.getScene().getWindow();
//				stage.close();
////				loginbtn.setOnAction(event -> {
////					MyapplicationApplication.showView(TempHzView.class, Modality.WINDOW_MODAL);
////				});
//				MyapplicationApplication.showView(TempHzView.class, Modality.WINDOW_MODAL);
//			} else {
//				alert.setContentText("请输入正确的密码！");
//				alert.showAndWait();
//			}
//		}

		if (yhxxList.size() < 1) {
			alert.setContentText("用户名错误，请检查用户名！");
			alert.showAndWait();
		}else {
			String encstr = yhxxList.get(0).getLoginPassword();
			String projectPathes = System.getProperty("user.dir") + "/src/main/resources/";
			String publicKeyPath = projectPathes + "/keys/publicKey.pem";
			String privateKeyPath = projectPathes + "/keys/privateKey.pem";
			try (BufferedReader privateKeyReader = new BufferedReader(new FileReader(privateKeyPath))) {
				StringBuilder privateKeyStringBuilder = new StringBuilder();
				String line;
				while ((line = privateKeyReader.readLine()) != null) {
					privateKeyStringBuilder.append(line);
				}
				String privateKeyString = privateKeyStringBuilder.toString();
//			System.out.println("Private Key (from PEM file): " + privateKeyString);
				// 读取公钥文件
				try (BufferedReader publicKeyReader = new BufferedReader(new FileReader(publicKeyPath))) {
					StringBuilder publicKeyStringBuilder = new StringBuilder();
					while ((line = publicKeyReader.readLine()) != null) {
						publicKeyStringBuilder.append(line);
					}
					String publicKeyString = publicKeyStringBuilder.toString();
//				System.out.println("Public Key (from PEM file): " + publicKeyString);
					PrivateKey privateKey1=readPrivateKeyFromPem(privateKeyString);
					PublicKey publicKey1 = readPublicKeyFromPem(publicKeyString);
					// 这里您可以继续对私钥和公钥进行处理，例如解码和使用它们进行加密/解密
					RSA rsa1 = new RSA(privateKey1,publicKey1);
//				// 私钥加密,公钥解密
//				System.out.println(new String(rsa1.encrypt("testaa", KeyType.PrivateKey)));
//				System.out.println(new String(rsa1.decrypt(rsa.encrypt("testaa", KeyType.PrivateKey), KeyType.PublicKey)));
//					byte[] aByte = StrUtil.bytes(encstr, CharsetUtil.CHARSET_UTF_8);
//					byte[] encrypt1 = rsa1.encrypt(aByte, KeyType.PrivateKey);
//					byte[] encrypt2 = rsa1.encrypt(aByte, KeyType.PublicKey);
					System.out.println(Base64.getEncoder().encodeToString(rsa1.encrypt(passwordStr, KeyType.PublicKey)));
					if (passwordStr.equals(new String(rsa1.decrypt(Base64.getDecoder().decode(encstr), KeyType.PrivateKey)))){
						Stage stage = (Stage) loginbtn.getScene().getWindow();
						stage.close();
						MyapplicationApplication.showView(TempHzView.class, Modality.WINDOW_MODAL);
					}else {
						alert.setContentText("请输入正确的密码！");
						alert.showAndWait();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}


	public Parent successpage() {
		HBox hbox = new HBox();
		Label label = new Label("登录成功");
		hbox.getChildren().add(label);
		hbox.setAlignment(Pos.CENTER);
		return hbox;
	}

	/**
	 * 判断账号和密码是否正确
	 */
	private List<Yhxx> checkLogin(String userName, String login_password) {
		String Password = SecureUtil.md5(login_password);
		return yhxxMapper.selectList(new QueryWrapper<Yhxx>().eq("login_name", userName).eq("login_password", Password).eq("gsbh",gsbh));
	}

}